import 'dart:convert';
import 'dart:math';

import 'package:dio/dio.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart' hide Response;
import 'package:ride_rex/generated/assets.dart';
import 'package:ylm_ui_kit/ylm_ui_kit.dart';

import '../main/discover/discover_bean.dart';
import '../net/common_global_url.dart';
import '../net/common_net.dart';
import '../sqlite/db_manager.dart';

class ApiFeed extends CommonApi {
  ApiFeed.feed()
      : super(CommonGlobalUrl.broadcasterWall, params: {
          "category": "Popular", // 分类固定传Popular
          "isPageMode": true,
          "isRemoteImageUrl": true, // 必须为true 否则返回的头像链接需要拼接
          "limit": 20,
          "page": 1,
          "tag": "All",
        });
}

class FeedService extends GetxService {
  static FeedService get instance => Get.find<FeedService>();

  Future fetchData() async {
    List<FeedUserBean> result = [];

    ///1.从Db中取用户列表
    var cache = await DbManager.getLocalUserList();
    if (cache.isNotEmpty) return;

    ///2.获取本地作者列表
    var localUserList = await getLocalUserList();

    ///2.1.获取oss视频列表
    var videoList = await getOssVideoList();

    ///3.取服务端返回的用户列表
    dynamic json = await ApiFeed.feed().post();
    var serverUserList = await CommonJson.getList(json, (json) => FeedUserBean.fromJson(json));

    int max = min(videoList.length, min(localUserList.length, serverUserList.length));

    ///4.合并本地和服务端的用户列表
    for (int i = 0; i < max; i++) {
      var serverUser = serverUserList[i];
      var localUser = localUserList[i];
      var video = videoList[i];

      ///服务端返回的用户信息同步到本地的用户信息
      localUser.userId = serverUser.userId;
      localUser.nickname = serverUser.nickname;
      localUser.avatar = serverUser.avatar;
      localUser.isFriend = serverUser.isFriend;
      localUser.localVideo = video;

      result.add(localUser);
    }

    ///5.去除没有userId的数据
    result.removeWhere((element) => element.userId.empty);

    ///6.写入本地Db中
    await DbManager.saveUserList(result);
  }

  ///获取oss视频列表
  Future<List<String>> getOssVideoList() async {
    return await getOssSourceList(
      data: List.generate(15, (index) => {"mediaPath": "RideRex/video/${index + 1}.mp4", "mediaType": "video"}),
    );
  }

  ///获取oss视频列表
  Future<List<String>> getOssSourceList({required List<Map<String, dynamic>> data}) async {
    final BaseOptions baseOptions = BaseOptions(
      baseUrl: CommonGlobalUrl.apiBaseRelease,
      connectTimeout: const Duration(seconds: 30),
      receiveTimeout: const Duration(seconds: 30),
      headers: await CommonNet.builder.initHeaders(),
    );
    final Dio dio = Dio(baseOptions);
    try {
      Response response = await dio.post(CommonGlobalUrl.oss, data: data);
      if (response.data is Map && response.data['data'] is List) {
        return (response.data['data'] as List).map((e) => e['mediaUrl'].toString()).toList();
      }
      return [];
    } catch (e) {
      print(e);
      return [];
    }
  }

  ///获取本地作者列表
  Future<List<FeedUserBean>> getLocalUserList() async {
    try {
      String result = await rootBundle.loadString(Assets.jsonRideRexUser);
      dynamic json = jsonDecode(result);
      if (json is List) {
        return await CommonJson.getList(json, (json) => FeedUserBean.fromJson(json));
      } else {
        return [];
      }
    } catch (_) {
      return [];
    }
  }

  @override
  void onClose() {
    super.onClose();
  }
}
